#!/usr/bin/evn python2.7
# _*_ coding: UTF-8 _*_

import hashlib
from django.http import HttpResponse,HttpRequest
from base_exception import *
import logging
from .string import str_random
import os

def get_request_parameters(request, *args):
    if not isinstance(request, HttpRequest):
        raise errIllegalObject

    arg_list = []
    try:
        for i in range(0, len(args)):
            if request.method == "POST":
                arg_list.append(request.POST[args[i]])
            elif request.method == "GET":
                arg_list.append(request.GET[args[i]])
        return arg_list
    except:
        raise errInvalidArguments


def http_file_read(path):
    """ this function will return a
        http response object that contains
        the file description like CONTENT, TYPE etc.
    """
    if not os.path.exists(path):
        raise errPathNotFound

    with open(path, "rb") as fp:
        content = fp.read()
        resp = HttpResponse(content, content_type='application/octet-stream')
        md5 = hashlib.md5()
        md5.update(content)
        resp["Content-MD5"] = md5.hexdigest()
        resp["Content-Length"] = os.path.getsize(path)
        resp["Content-Disposition"] = 'attachment;filename=' + os.path.basename(path)
        return resp


def http_file_write(request, key, path):
    def _save_file(path, f):
        with open(path, "wb+") as fp:
            for chunk in f.chunks():
                fp.write(chunk)

    if not isinstance(request, HttpRequest):
        raise errIllegalObject
    files = []

    for f in request.FILES.getlist(key):
        if os.path.isdir(path):
            path = path+"/"+f.name
        if os.path.exists(path):
            strs = path.rsplit(".", 1)
            path = "%s_%s"%(strs[0], str_random(8, ""))
            if len(strs) > 1:
                path += "."+strs[1]
        try:
            _save_file(path, f)
            files.append(path)
        except Exception as e:
            logging.error("Writed file %s failed due to %s"%(path, e.message))

    return files


def model_find(cls, **kwargs):
    try:
        return cls.objects.get(**kwargs)
    except cls.ObjectDoesNotExist:
        return None
    except Exception as e:
        logging.error(e.message)
        raise errException


def model_create(cls, **kwargs):
    try:
        obj = cls(**kwargs)
        obj.save(force_insert=True)
        return obj
    except cls.ObjectDoesExist:
        raise errObjectDoesExist
    except Exception as e:
        logging.error(e.message)
        raise errException


def model_set(obj, **kwargs):
    try:
        for key in kwargs.keys():
            if hasattr(obj, key):
                setattr(obj, key, kwargs[key])
        obj.save(force_update=True)
    except Exception as e:
        logging.error(e.message)
        raise errException


from PIL import Image, ImageDraw, ImageFont, ImageFilter


def generate_code_image(text):
    # set width and height.
    size = (100, 40)
    # set the background color.
    bgcolor = (52, 53, 55)
    # set font color
    fontcolor = (0, 0, 255)
    number = len(text)
    width, height = size
    image = Image.new('RGBA', (width, height), bgcolor)  # 创建图片
    # font = ImageFont.load_default() # 验证码的字体
    font = ImageFont.truetype()
    draw = ImageDraw.Draw(image)  # 创建画笔
    font_width, font_height = font.getsize(text)
    draw.text(((width - font_width) / number, (height - font_height) / number), text, \
              font=font, fill=fontcolor)  # 填充字符串
    image = image.filter(ImageFilter.EDGE_ENHANCE_MORE)  # 滤镜，边界加强
    return image
    #
    # img_name = '{0}/{1}.png'.format(path, text)
    # image.save(img_name)  # 保存验证码图片
    # return '{0}.png'.format(text)


import logging
def logging_run(cb, msg=None, err_exit=False, *args, **kwargs):
    if not msg:
        msg = "Running "+cb.__name__

    logging.info(msg)
    try:
        cb(*args, **kwargs)
        logging.info("[ OK ]"+msg)
    except Exception as e:
        logging.error("[ ERROR ]"+msg)
